DROP PROCEDURE [dbo].[pr0092] 
GO
----- Purpose: Tao du lieu ngam cho chuc nang cap quyen theo du lieu

CREATE  PROCEDURE [dbo].[pr0092] 
	@DivisionID as varchar(20),
	@ModuleID as varchar(20),
	@DataID as varchar(20),
	@DataName as varchar(100),
	@DataType as char(2),
	@Date as datetime,
	@UserID as varchar(20),
	@Status as char(1)
AS
SET NOCOUNT	 OFF

	IF @Status='A' --Neu trang thai la them moi
		If @DataType<>'PE'
		BEGIN
			If not exists (SELECT DivisionID + DataID + DataType FROM tb0076 WHERE DivisionID + DataID + DataType = @DivisionID + @DataID + @DataType )
			BEGIN
				INSERT INTO tb0076(DivisionID,ModuleID,DataID,DataName,DataType,CreateDate,CreateUserID) 
				SELECT @DivisionID,ModuleID,@DataID,@DataName, @DataType, getDate(), @UserID
				FROM tb0078
			END
			
			If not exists (SELECT DivisionID + DataID + DataType FROM tb0075 WHERE DivisionID + DataID + DataType = @DivisionID + @DataID + @DataType )
			BEGIN
				INSERT INTO tb0075(DivisionID, ModuleID, GroupID, DataID, DataType, Permission,CreateDate,CreateUserID) 
				SELECT @DivisionID,ModuleID,GroupID,@DataID,@DataType, 1,getDate(),@UserID FROM tb0070 CROSS JOIN tb0078
			END
		END
		else
		BEGIN
			If not exists (SELECT DivisionID + ModuleID + DataID + DataType FROM tb0076 WHERE DivisionID + ModuleID + DataID + DataType = @DivisionID + @ModuleID + @DataID + @DataType )
			BEGIN
				INSERT INTO tb0076(DivisionID,ModuleID,DataID,DataName,DataType,CreateDate,CreateUserID) 
				SELECT @DivisionID,@ModuleID,@DataID,@DataName, @DataType, getDate(), @UserID
			END
			
			If not exists (SELECT DivisionID + ModuleID + DataID + DataType FROM tb0075 WHERE DivisionID + ModuleID + DataID + DataType = @DivisionID + @ModuleID + @DataID + @DataType )
			BEGIN
				INSERT INTO tb0075(DivisionID, ModuleID, GroupID, DataID, DataType, Permission,CreateDate,CreateUserID) 
				SELECT @DivisionID,@ModuleID,GroupID,@DataID,@DataType, 1,getDate(),@UserID FROM tb0070
			END
		END	
	
	IF @Status='E' -- Neu trang thai la sua
		BEGIN
			UPDATE tb0076 SET DataName = @DataName, LastModifyDate=getDate(), LastModifyUserID=@UserID WHERE DataID=@DataID And DataType = @DataType
		END
	IF @Status='D' --Neu trang thai la xoa
		BEGIN
			DELETE tb0075 WHERE DataID=@DataID And DataType = @DataType
			DELETE tb0076 WHERE DataID=@DataID And DataType = @DataType
		END 
SET NOCOUNT ON


GO